/*
 * @Author: boyyang
 * @Date: 2022-01-07 16:00:23
 * @LastEditTime: 2022-01-07 17:59:48
 * @LastEditors: boyyang
 * @Description: 
 * @FilePath: \boyyang\src\components\loadingBar\loadingBarProvider.tsx
 */

import { defineComponent, h, Fragment, ref, provide, renderSlot, computed } from 'vue'
const React = { createElement: h, Fragment: Fragment }

import { ILoadingBarApi, loadingBarApiInjectKey } from './loadingBarTypes'
import './loadingBar.scss'
export default defineComponent({
    name: 'LoadingBarProvider',
    setup() {
        const api: ILoadingBarApi = {
            start() {
                loadingBarBegin()
            },
            finish() {
                loadingBarFinsh()
            }
        }

        const isShow = ref<boolean>(false)
        const pos = ref<string>('25%')

        const loadingBarBegin = () => {
            isShow.value = false
            let timer = setTimeout(() => {
                isShow.value = true
                clearTimeout(timer)
            }, 500);
        }
        const loadingBarFinsh = () => {
            pos.value = '100%'
            let num = 25
            setInterval(() =>{
              num += 5
              pos.value = `${num}%`
            }, 500)
        }

        provide(loadingBarApiInjectKey, api)

        return {
            isShow,
            pos,
            cssVars: computed(() => {
                return {
                    '--pos': pos.value,
                }
            })
        }
    },
    render() {
        const { isShow, cssVars } = this
        return (
            <>
                {renderSlot(this.$slots, 'default')}
                {isShow ? (
                    <div class="loading-bar-wrapper" style={[cssVars as any]}>
                        <div class="loading-bar-track"></div>
                    </div>
                ) : ''}

            </>
        )
    }
})
